package eiisan.service.user.impl;

import eiisan.config.aop.validation.annotation.Check;
import eiisan.constant.enums.user.UserStatusEnum;
import eiisan.constant.errors.code.ErrorCode;
import eiisan.constant.errors.exception.ServiceException;
import eiisan.dao.domain.user.Role;
import eiisan.dao.domain.user.User;
import eiisan.dao.param.user.Doregister;
import eiisan.dao.repository.user.UserRepository;
import eiisan.service.user.LoginService;
import eiisan.service.user.UserService;
import eiisan.util.model.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Date;

/**
 * UserServiceImpl
 * @author gragonfly
 * @date 2019/7/6
 **/
@Slf4j
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private LoginService loginService;

    @Check
    @Override
    public Result register(@Valid @NotNull Doregister param) {
        try {
            User user = new User();
            user.setCreateTime(new Date());
            user.setName(param.getName());
            user.setPassword(passwordEncoder.encode(param.getPassword()));
            user.setNickname(param.getNickname());
            user.setEmail(param.getEmail());
            user.setPhone(param.getPhone());
            user.setStatus(UserStatusEnum.NORMAL.getVal());
            //暂时写死
            Role role = new Role();
            role.setId(1L);
            user.setRole(role);
            userRepository.save(user);
            return Result.success();
        } catch (Exception e) {
            log.error("[register]", e);
            throw new ServiceException(ErrorCode.USER_SERVICE_ERROR);
        }
    }

    @Override
    public Result logOff() {
        return null;
    }
}
